package com.xzwzz.kotlindemo.city

import com.csvreader.CsvReader
import org.apache.poi.openxml4j.exceptions.InvalidFormatException
import org.apache.poi.ss.usermodel.Cell
import org.apache.poi.ss.usermodel.Sheet
import org.apache.poi.ss.usermodel.Workbook
import org.apache.poi.ss.usermodel.WorkbookFactory
import java.io.File
import java.io.FileInputStream
import java.io.IOException
import java.util.ArrayList
import java.nio.charset.Charset
import com.xzwzz.kotlindemo.FindCityUtil
import java.util.LinkedHashMap
import java.util.regex.Pattern
import java.io.BufferedWriter
import java.io.OutputStreamWriter
import java.io.FileOutputStream


object categoryUtil {

    @Throws(IOException::class)
    private fun getWorkbook(path: String): Workbook? {

        var wb: Workbook? = null
        try {
            FileInputStream(path).use { `is` -> wb = WorkbookFactory.create(`is`) }
        } catch (e: InvalidFormatException) {
            e.printStackTrace()
        }

        return wb
    }

    private fun readSheet(sheet: Sheet): List<List<String>> {
        val lists = ArrayList<List<String>>()
        // 第一行为标题
        for (row in sheet) {
            val list = ArrayList<String>()
            for (cell in row) {
                // 根据不同类型转化成字符串
                cell.cellType = Cell.CELL_TYPE_STRING
                list.add(cell.stringCellValue)
            }
            lists.add(list)
        }
        return lists
    }

    //读取csv文件
    @Throws(Exception::class)
    fun readCsv(filePath: String): List<Array<String>> {
        val csvList = ArrayList<Array<String>>()
        if (isCsv(filePath)) {
            val reader = CsvReader(filePath, ',', Charset.forName("UTF-8"))
            reader.readHeaders() // 跳过表头   如果需要表头的话，不要写这句。
            while (reader.readRecord()) { //逐行读入除表头的数据
                csvList.add(reader.values)
            }
            reader.close()
        } else {
            println("此文件不是CSV文件！")
        }
        return csvList
    }

    //判断是否是csv文件
    private fun isCsv(fileName: String): Boolean {
        return fileName.matches("^.+\\.(?i)(csv)$".toRegex())
    }

    //拆分表
    fun execute(path: String, isDir: Boolean, regex: String) {
        isDir
        var result = mutableListOf<LoginBean>()

        try {
            val list = readCsv(path)

            for (r in list.indices) {
                val args = list.get(r)
                val map = getSheng(args[5], regex = regex)

                val item = LoginBean(
                    args[0],
                    args[1],
                    args[2],
                    args[3],
                    args[4],
                    args[5],
                    args[6],
                    args[7],
                    map["1"] ?: "",
                    map["2"] ?: "",
                    map["3"] ?: "",
                    args[11]
                )
                result.add(item)
//                if (item.省 != "") {
//                    println(item)
//                }
            }
            WriteCsv(result)
        } catch (e: Exception) {
            e.printStackTrace()
        }

    }

    private fun getSheng(vararg args: String, regex: String): MutableMap<String, String> {
        val map = mutableMapOf<String, String>()
        args.forEach {
            //            val m = addressResolution(it)[0]

//            val list = regex.takeWhile { value.contains(it) || value.equals(it) }
//            if (list.size != 0) {
//                println(list.first())
//                return FindCityUtil.cityNo[list.first()] ?: "xzwzz"
//            }
            val r = Regex("$regex{2,}")
            if (r.matches(it)) {
                val value = r.find(it)?.groupValues?.first() ?: ""
                map.put("1", FindCityUtil.city1No[value] ?: "");
                map.put("2", FindCityUtil.city2No[value] ?: "");
            }
        }
        return map
    }

    fun exportCsv(file: File, dataList: List<String>?): Boolean {
        var isSucess = false

        var out: FileOutputStream? = null
        var osw: OutputStreamWriter? = null
        var bw: BufferedWriter? = null
        try {
            out = FileOutputStream(file)
            osw = OutputStreamWriter(out)
            bw = BufferedWriter(osw)
            if (dataList != null && !dataList.isEmpty()) {
                for (data in dataList) {
                    bw.append(data).append("\r")
                }
            }
            isSucess = true
        } catch (e: Exception) {
            isSucess = false
        } finally {
            if (bw != null) {
                try {
                    bw.close()
                    bw = null
                } catch (e: IOException) {
                    e.printStackTrace()
                }

            }
            if (osw != null) {
                try {
                    osw.close()
                    osw = null
                } catch (e: IOException) {
                    e.printStackTrace()
                }

            }
            if (out != null) {
                try {
                    out.close()
                    out = null
                } catch (e: IOException) {
                    e.printStackTrace()
                }

            }
        }

        return isSucess
    }

    /**
     * 写入CSV文件
     */
    fun WriteCsv(item: List<LoginBean>) {
        val csvFilePath = "/Users/xzwzz/Desktop/save.csv"
        val s = mutableListOf<String>("id,name,tel,address,school,intention,createtime,nianji,省,市,区,source")
        s.addAll(item.map {
            "${it.id},${
            it.name.replace(",","")},${
            it.tel.replace(",","")},${
            it.address.replace(",","")},${
            it.school.replace(",","")},${
            it.intention.replace(",","")},${
            it.createtime.replace(",","")},${
            it.nianji.replace(",","")},${
            it.省},${
            it.市},${
            it.区},${
            it.source.replace(",","")}"
        })
        exportCsv(File(csvFilePath), s)
//        item.forEach {
//            try {
//                val wr = CsvWriter(csvFilePath, ',', Charset.forName("SJIS"))//日文编码
//                val contents = arrayOf(
//                    it.id,
//                    it.name,
//                    it.tel,
//                    it.address,
//                    it.school,
//                    it.intention,
//                    it.createtime,
//                    it.nianji,
//                    it.省,
//                    it.市,
//                    it.区,
//                    it.source
//                )
//                wr.writeRecord(contents)
//                wr.close()
//            } catch (e: IOException) {
//                e.printStackTrace()
//            }
//        }

    }


    fun addressResolution(address: String): List<Map<String, String?>> {
        val regex =
            "(?<province>[^省]+自治区|.*?省|.*?行政区|.*?市){0,1}(?<city>[^市]+自治州|.*?地区|.*?行政单位|.+盟|市辖区|.*?市|.*?县){0,1}(?<county>[^县]+县|.+区|.+市|.+旗|.+海域|.+岛)?(?<town>[^区]+区|.+镇)?(?<village>.*)"
        val m = Pattern.compile(regex).matcher(address)
        var province: String? = null
        var city: String? = null
        var county: String? = null
        var town: String? = null
        var village: String? = null
        val table = ArrayList<Map<String, String?>>()
        var row: MutableMap<String, String?>? = null
        while (m.find()) {
            row = LinkedHashMap()
            province = m.group("province")
            row["province"] = if (province == null) null else province!!.trim { it <= ' ' }
            city = m.group("city")
            row["city"] = if (city == null) null else city!!.trim { it <= ' ' }
            county = m.group("county")
            row["county"] = if (county == null) null else county!!.trim { it <= ' ' }
            town = m.group("town")
            row["town"] = if (town == null) null else town!!.trim { it <= ' ' }
            village = m.group("village")
            row["village"] = if (village == null) null else village!!.trim { it <= ' ' }
            table.add(row)
        }
        return table
    }

}